package com.taylor.seckill.controller;

import com.taylor.seckill.pojo.Order;
import com.taylor.seckill.pojo.SeckillOrder;
import com.taylor.seckill.pojo.User;
import com.taylor.seckill.rabbitmq.MQSender;
import com.taylor.seckill.service.IGoodsService;
import com.taylor.seckill.service.IOrderService;
import com.taylor.seckill.service.ISeckillOrderService;
import com.taylor.seckill.util.RedisUtil;
import com.taylor.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author taylor
 * @Description: TODO
 * @date 2021/4/12 23:06
 */
@Controller
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    IGoodsService goodsService;
    @Autowired
    ISeckillOrderService seckillOrderService;

    @Autowired
    IOrderService orderService;

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    MQSender mqSender;

    @RequestMapping("/doSeckill")
    public String seckill(Model model, User user, @RequestParam("goodsId") long goodId){
        // 判断是否登录
        if(user == null){
            return "login";
        }
        // 查库存
        GoodsVo goods = goodsService.findGoodsVoByID(goodId);
        int stock = goods.getGoodsStock();
        if(stock < 0){
            model.addAttribute("errmsg", "宝贝已经被抢光了哦");
            return "secKillFail";
        }
        // 判断是否重复秒杀
        // TODO 枚举待优化
//        QueryWrapper<SeckillOrder> seckillOrderQueryWrapper = new QueryWrapper<>();
//        SeckillOrder seckillOrder = seckillOrderService.getOne(seckillOrderQueryWrapper.eq("user_id", user.getId()).eq("goods_id", goodId));

        SeckillOrder seckillOrder  = (SeckillOrder)redisUtil.get("order:" + user.getId() + ":" + goodId);
        if (seckillOrder != null){
            model.addAttribute("errmsg", "只能秒杀一次");
            return "secKillFail";
        }
        // 减库存，下订单
        Order order = orderService.doSeckill(user, goods);
        // TODO 模拟消息队列异步下单 伪代码
        Object msg = null;
        mqSender.sendOrderMessage(msg);

        model.addAttribute("order",order);
        model.addAttribute("goods", goods);
        return "orderDetail";
    }
}
